<template>
	<view class="account-list">
		<!-- 头部统计 -->
		<view class="header-stats">
			<view class="stat-item">
				<text class="stat-label">收入</text>
				<text class="stat-value income">+{{ stats.income.toFixed(2) }}</text>
			</view>
			<view class="stat-item">
				<text class="stat-label">支出</text>
				<text class="stat-value expense">-{{ stats.expense.toFixed(2) }}</text>
			</view>
			<view class="stat-item">
				<text class="stat-label">结余</text>
				<text class="stat-value" :class="stats.balance >= 0 ? 'income' : 'expense'">
					{{ stats.balance.toFixed(2) }}
				</text>
			</view>
		</view>

		<!-- 筛选栏 -->
		<view class="filter-bar">
			<view class="filter-tabs">
				<text 
					class="filter-tab" 
					:class="{ active: filterType === '' }"
					@tap="changeFilter('')"
				>全部</text>
				<text 
					class="filter-tab" 
					:class="{ active: filterType === '支出' }"
					@tap="changeFilter('支出')"
				>支出</text>
				<text 
					class="filter-tab" 
					:class="{ active: filterType === '收入' }"
					@tap="changeFilter('收入')"
				>收入</text>
			</view>
		</view>

		<!-- 记账列表 -->
		<scroll-view 
			class="record-list" 
			scroll-y 
			@scrolltolower="loadMore"
			refresher-enabled
			:refresher-triggered="refreshing"
			@refresherrefresh="onRefresh"
		>
			<view v-if="groupedRecords.length === 0" class="empty-state">
				<text class="empty-icon">📝</text>
				<text class="empty-text">暂无记账记录</text>
				<button class="add-btn-small" @tap="goToAdd">立即记账</button>
			</view>

			<view v-for="(group, index) in groupedRecords" :key="index" class="date-group">
				<view class="date-header">
					<text class="date-text">{{ group.date }}</text>
					<text class="date-summary">
						收入 {{ group.income.toFixed(2) }} | 支出 {{ group.expense.toFixed(2) }}
					</text>
				</view>

				<view 
					v-for="item in group.records" 
					:key="item._id" 
					class="record-item"
					@tap="showDetail(item)"
				>
					<view class="record-left">
						<view class="record-icon">
							<text class="iconfont" :class="item.category_icon || 'icon-qita'"></text>
						</view>
						<view class="record-info">
							<text class="record-category">{{ item.category_name || '未分类' }}</text>
							<text class="record-note" v-if="item.note">{{ item.note }}</text>
						</view>
					</view>
					<view class="record-right">
						<text 
							class="record-amount" 
							:class="item.type === '收入' ? 'income' : 'expense'"
						>
							{{ item.type === '收入' ? '+' : '-' }}{{ item.amount.toFixed(2) }}
						</text>
					</view>
				</view>
			</view>

			<view v-if="hasMore" class="load-more">
				<text>{{ loading ? '加载中...' : '上拉加载更多' }}</text>
			</view>
			<view v-else-if="groupedRecords.length > 0" class="no-more">
				<text>没有更多了</text>
			</view>
		</scroll-view>

		<!-- 悬浮添加按钮 -->
		<view class="fab" @tap="goToAdd">
			<text class="fab-icon">+</text>
		</view>
	</view>
</template>

<script>
export default {
	data() {
		return {
			records: [],
			stats: {
				income: 0,
				expense: 0,
				balance: 0
			},
			filterType: '', // '', '支出', '收入'
			page: 1,
			pageSize: 20,
			hasMore: true,
			loading: false,
			refreshing: false
		}
	},
	computed: {
		// 按日期分组记录
		groupedRecords() {
			const groups = {}
			this.records.forEach(item => {
				const date = item.date
				if (!groups[date]) {
					groups[date] = {
						date: this.formatDate(date),
						records: [],
						income: 0,
						expense: 0
					}
				}
				groups[date].records.push(item)
				if (item.type === '收入') {
					groups[date].income += item.amount
				} else {
					groups[date].expense += item.amount
				}
			})
			
			// 转换为数组并排序
			return Object.values(groups).sort((a, b) => {
				return b.date.localeCompare(a.date)
			})
		}
	},
	onLoad() {
		this.loadRecords()
		this.loadStatistics()
	},
	onShow() {
		// 从添加页面返回时刷新列表
		const pages = getCurrentPages()
		const currPage = pages[pages.length - 1]
		if (currPage.$page.options.refresh) {
			this.onRefresh()
		}
	},
	methods: {
		// 加载记账记录
		async loadRecords(refresh = false) {
			if (this.loading) return
			
			this.loading = true
			
			try {
				const accountObj = uniCloud.importObject('account')
				const res = await accountObj.listRecords({
					limit: this.pageSize,
					skip: refresh ? 0 : (this.page - 1) * this.pageSize,
					type: this.filterType || undefined
				})
				
				if (res.code === 0) {
					if (refresh) {
						this.records = res.data
						this.page = 1
					} else {
						this.records = this.records.concat(res.data)
					}
					
					this.hasMore = res.data.length >= this.pageSize
					this.page++
				}
			} catch (e) {
				console.error('加载记录失败', e)
				uni.showToast({
					title: '加载失败',
					icon: 'none'
				})
			} finally {
				this.loading = false
				this.refreshing = false
			}
		},
		
		// 加载统计数据
		async loadStatistics() {
			try {
				const accountObj = uniCloud.importObject('account')
				const res = await accountObj.getStatistics()
				
				if (res.code === 0) {
					this.stats = res.data
				}
			} catch (e) {
				console.error('加载统计失败', e)
			}
		},
		
		// 切换筛选
		changeFilter(type) {
			this.filterType = type
			this.page = 1
			this.records = []
			this.loadRecords(true)
		},
		
		// 下拉刷新
		onRefresh() {
			this.refreshing = true
			this.loadRecords(true)
			this.loadStatistics()
		},
		
		// 加载更多
		loadMore() {
			if (!this.hasMore || this.loading) return
			this.loadRecords()
		},
		
		// 显示详情（长按可删除/编辑）
		showDetail(item) {
			uni.showActionSheet({
				itemList: ['查看详情', '删除'],
				success: async (res) => {
					if (res.tapIndex === 0) {
						// 查看详情
						this.goToEdit(item)
					} else if (res.tapIndex === 1) {
						// 删除
						this.deleteRecord(item._id)
					}
				}
			})
		},
		
		// 删除记录
		async deleteRecord(id) {
			uni.showModal({
				title: '确认删除',
				content: '确定要删除这条记录吗？',
				success: async (res) => {
					if (res.confirm) {
						try {
							const accountObj = uniCloud.importObject('account')
							const result = await accountObj.deleteRecord(id)
							
							if (result.code === 0) {
								uni.showToast({
									title: '删除成功',
									icon: 'success'
								})
								this.onRefresh()
							}
						} catch (e) {
							uni.showToast({
								title: '删除失败',
								icon: 'none'
							})
						}
					}
				}
			})
		},
		
		// 跳转到添加页面
		goToAdd() {
			uni.navigateTo({
				url: '/pages/account/add'
			})
		},
		
		// 跳转到编辑页面
		goToEdit(item) {
			uni.navigateTo({
				url: `/pages/account/add?id=${item._id}`
			})
		},
		
		// 格式化日期
		formatDate(dateStr) {
			const date = new Date(dateStr)
			const today = new Date()
			const yesterday = new Date(today)
			yesterday.setDate(yesterday.getDate() - 1)
			
			if (dateStr === this.getDateStr(today)) {
				return '今天'
			} else if (dateStr === this.getDateStr(yesterday)) {
				return '昨天'
			} else {
				return dateStr
			}
		},
		
		// 获取日期字符串
		getDateStr(date) {
			const year = date.getFullYear()
			const month = String(date.getMonth() + 1).padStart(2, '0')
			const day = String(date.getDate()).padStart(2, '0')
			return `${year}-${month}-${day}`
		}
	}
}
</script>

<style scoped>
.account-list {
	display: flex;
	flex-direction: column;
	height: 100vh;
	background-color: #f5f5f5;
}

/* 头部统计 */
.header-stats {
	display: flex;
	justify-content: space-around;
	background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
	padding: 30rpx 20rpx;
	color: #fff;
}

.stat-item {
	display: flex;
	flex-direction: column;
	align-items: center;
}

.stat-label {
	font-size: 28rpx;
	opacity: 0.9;
	margin-bottom: 10rpx;
}

.stat-value {
	font-size: 36rpx;
	font-weight: bold;
}

.stat-value.income {
	color: #52c41a;
}

.stat-value.expense {
	color: #ff4d4f;
}

/* 筛选栏 */
.filter-bar {
	background-color: #fff;
	padding: 20rpx;
	border-bottom: 1px solid #eee;
}

.filter-tabs {
	display: flex;
	gap: 20rpx;
}

.filter-tab {
	flex: 1;
	text-align: center;
	padding: 12rpx 0;
	border-radius: 8rpx;
	font-size: 28rpx;
	color: #666;
	background-color: #f5f5f5;
	transition: all 0.3s;
}

.filter-tab.active {
	background-color: #667eea;
	color: #fff;
}

/* 记录列表 */
.record-list {
	flex: 1;
	padding: 20rpx;
}

.empty-state {
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: center;
	padding: 100rpx 0;
}

.empty-icon {
	font-size: 100rpx;
	margin-bottom: 20rpx;
}

.empty-text {
	font-size: 28rpx;
	color: #999;
	margin-bottom: 40rpx;
}

.add-btn-small {
	background-color: #667eea;
	color: #fff;
	border: none;
	font-size: 28rpx;
	padding: 12rpx 40rpx;
	border-radius: 50rpx;
}

/* 日期分组 */
.date-group {
	margin-bottom: 20rpx;
}

.date-header {
	display: flex;
	justify-content: space-between;
	align-items: center;
	padding: 10rpx 20rpx;
	background-color: #f5f5f5;
	border-radius: 8rpx;
	margin-bottom: 10rpx;
}

.date-text {
	font-size: 28rpx;
	color: #333;
	font-weight: bold;
}

.date-summary {
	font-size: 24rpx;
	color: #999;
}

/* 记录项 */
.record-item {
	display: flex;
	justify-content: space-between;
	align-items: center;
	background-color: #fff;
	padding: 24rpx;
	border-radius: 12rpx;
	margin-bottom: 12rpx;
	box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
}

.record-left {
	display: flex;
	align-items: center;
	flex: 1;
}

.record-icon {
	width: 80rpx;
	height: 80rpx;
	border-radius: 50%;
	background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
	display: flex;
	align-items: center;
	justify-content: center;
	margin-right: 20rpx;
}

.record-icon .iconfont {
	font-size: 40rpx;
	color: #fff;
}

.record-info {
	display: flex;
	flex-direction: column;
}

.record-category {
	font-size: 30rpx;
	color: #333;
	margin-bottom: 8rpx;
}

.record-note {
	font-size: 24rpx;
	color: #999;
}

.record-right {
	display: flex;
	align-items: center;
}

.record-amount {
	font-size: 34rpx;
	font-weight: bold;
}

.record-amount.income {
	color: #52c41a;
}

.record-amount.expense {
	color: #ff4d4f;
}

/* 加载更多 */
.load-more,
.no-more {
	text-align: center;
	padding: 20rpx;
	font-size: 24rpx;
	color: #999;
}

/* 悬浮按钮 */
.fab {
	position: fixed;
	right: 30rpx;
	bottom: 100rpx;
	width: 100rpx;
	height: 100rpx;
	border-radius: 50%;
	background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
	box-shadow: 0 4rpx 12rpx rgba(102, 126, 234, 0.4);
	display: flex;
	align-items: center;
	justify-content: center;
	z-index: 999;
}

.fab-icon {
	font-size: 60rpx;
	color: #fff;
	font-weight: 300;
}
</style>

